<template>
  <div class="app-container">
    <el-form :inline="true"
             :model="filters"
             ref="refForm"
             class="demo-form-inline filter-container">
      <el-form-item prop="time"
                    label="查询时间">
        <el-date-picker
          v-model="form.orderTime"
          class="filter-item"
          type="datetimerange"
          align="right"
          unlink-panels
          :range-separator="$t('language.finance.recharge.to')"
          :start-placeholder="$t('language.finance.recharge.startDate')"
          :end-placeholder="$t('language.finance.recharge.endDate')"
          :default-time="['00:00:00', '23:59:59']"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerDayStep">
        </el-date-picker>
      </el-form-item>
      <el-form-item prop="time"
                    label="派奖时间">
        <el-date-picker v-model="form.payoutTime"
                        class="filter-item"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :default-time="['00:00:00', '23:59:59']"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        align="center"
                        :picker-options="pickerDayStep"
                        unlink-panels>
        </el-date-picker>
      </el-form-item>
      <el-form-item prop="time"
                    label="同步时间">
        <el-date-picker v-model="form.createTime"
                        class="filter-item"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        align="right"
                        unlink-panels
                        :default-time="['00:00:00', '23:59:59']">
        </el-date-picker>
      </el-form-item>
       <el-form-item prop="time"
                    label="统计时间">
        <el-date-picker v-model="form.timestamp"
                        class="filter-item"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        align="right"
                        unlink-panels
                        :default-time="['00:00:00', '23:59:59']">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="下注金额："
                    prop="minAmount">
        <el-input v-model="filters.minAmount"
                  style="width: 100px;" />
      </el-form-item>
      <span class="form-center-tip">至</span>
      <el-form-item prop="maxAmount">
        <el-input v-model="filters.maxAmount"
                  style="width: 100px;" />
      </el-form-item>
      <el-form-item label="公司输赢："
                    prop="minProfit">
        <el-input v-model="filters.minProfit"
                  style="width: 100px;" />
      </el-form-item>
      <span class="form-center-tip">至</span>
      <el-form-item prop="maxProfit">
        <el-input v-model="filters.maxProfit"
                  style="width: 100px;" />
      </el-form-item>
      <el-form-item label="游戏平台："
                    prop="channelId">
        <el-select :collapse-tags="true"
                   multiple
                   v-model="filters.gamePlatformId">
          <el-option v-for="item in consts.GAME_ID"
                     v-show="!lotteryArray.includes(item.value)"
                     :key="item.gamePlatformId"
                     :label="item.title"
                     :value="item.gamePlatformId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="子游戏平台：" prop="agGameId">
        <el-select v-model="filters.agGameId" :disabled="subGameFlag">
          <el-option v-for="item in agSubGame"
                     :key="item.value"
                     :label="item.title"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
       <el-form-item label="游戏账户名:"
                    prop="merUsername">
        <el-input v-model="filters.merUsername"
                  style="width: 100px;" />
      </el-form-item>
      <el-form-item label="会员账户名："
                    prop="username">
        <el-input v-model="filters.username"
                  style="width: 200px;" />
      </el-form-item>
      <el-form-item label="所属代理："
                    prop="proxy">
        <el-input v-model="filters.proxy"
                  style="width: 100px;" />
      </el-form-item>
      <el-form-item label="注单号："
                    prop="orderId">
        <el-input v-model="filters.orderId"
                  styltee="width: 100px;" />
      </el-form-item>
      <el-form-item label="注单状态："
                    prop="status">
        <el-select :collapse-tags="true"
                   multiple
                   v-model="filters.status">
          <el-option v-for="item in consts.NOTE_STATUS"
                     :key="item.value"
                     :label="item.title"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="第三方订单号："
                    prop="merOrderId">
        <el-input v-model="filters.merOrderId"
                  styltee="width: 100px;" />
      </el-form-item>
      <el-form-item v-if="roleCheck('virtual')"
                    class="with-pre-select"
                    label="数据类型">
        <el-select v-model="filters.isFake">
          <el-option v-for="item in consts.STATISTICS_RANGE"
                     :key="item.value"
                     :label="item.title"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-button type="primary"
                 v-waves
                 icon="el-icon-search"
                 @click="submitFilterForm(filters)">搜索</el-button>
      <el-button @click="resetFilter">重置</el-button>
    </el-form>
    <div style="padding: 20px 0">
      <el-button-group>
        <el-button size="mini"
                   type="primary"
                   icon="el-icon-download"
                   v-if="roleCheck('export')"
                   @click="downLoadExcel({ action : 'getExportExcel' })">导出
        </el-button>
      </el-button-group>
    </div>
    <el-table :data="tableData.list"
              v-loading="loading"
              element-loading-text="给我一点时间"
              border
              fit
              highlight-current-row
              show-summary
              :summary-method="getSummaries"
              style="width: 100%"
              max-height='540'>
      <el-table-column label="第三方订单号"
                       align="center"
                       width="110px">
        <template slot-scope="{row}">
          {{row.merOrderId}}
        </template>
      </el-table-column>
      <el-table-column label="下注时间"
                       align="center"
                       width="90px">
        <template slot-scope="{row}">
          {{row.createTime | toTime}}
        </template>
      </el-table-column>
      <el-table-column label="派彩时间"
                       align="center"
                       width="90px">
        <template slot-scope="{row}">
          {{row.payoutTime | toTime}}
        </template>
      </el-table-column>
      <el-table-column label="账户名"
                       align="center">
        <template slot-scope="{row}">
          {{row.userName}}
        </template>
      </el-table-column>

      <el-table-column label="游戏账户名"
                       align="center">
        <template slot-scope="{row}">
          {{row.merUsername}}
        </template>
      </el-table-column>
      <el-table-column label="游戏平台"
                       align="center">
        <template slot-scope="{row}">
          {{row.channelName}}
        </template>
      </el-table-column>
      <el-table-column label="子游戏"
                       align="center">
        <template slot-scope="{row}">
          {{row.gameName}}
        </template>
      </el-table-column>
      <el-table-column label="投注内容"
                       align="center"
                       width="160px">
        <template slot-scope="{row}">
          <span v-if="row.game == 3"
                style="color: #409eff;cursor: pointer"
                @click="openDialog({dialogName: 'game-dialog', props: row })">
            {{ checkShowDetail(row) }}
          </span>
          <span v-else>
            {{ checkShowDetail(row) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="游戏结果"
                       align="center"
                       width="160px">
        <template slot-scope="{row}">
          {{row.gameResult}}
        </template>
      </el-table-column>
      <el-table-column label="注单状态"
                       align="center"
                       width="82px">
        <template slot-scope="{row}">
          <el-tag>
            {{row.status | toConverter('NOTE_STATUS')}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="下注金额"
                       align="center"
                       prop="amount">
        <template slot-scope="{row}">
          <span v-if="row.betWays==0"> {{row.amount | currency}}</span> <!--平台类-->
          <span v-else> {{row.playerAmount | currency}}</span> <!--玩家类-->
        </template>
      </el-table-column>
      <el-table-column label="派彩金额"
                       align="center"
                       prop="prize">
        <template slot-scope="{row}">
          <span v-if="row.betWays==0"> {{row.prize | currency}}</span> <!--平台类-->
          <span v-else> {{row.playerPrize | currency}}</span> <!--玩家类-->
        </template>
      </el-table-column>
      <el-table-column label="同步时间"
                       align="center"
                       width="90px">
        <template slot-scope="{row}">
          {{row.syncTime | toTime}}
        </template>
      </el-table-column>
      <el-table-column label="输赢"
                       align="center"
                       prop="totalWin">
        <template slot-scope="{row}">
          {{row.totalWin | currency}}
           <!-- <span v-if="row.betWays==0"> {{row.win | currency}}</span> <!--平台类-->
           <!--<span v-else> {{ row.playerWin  | currency}}</span> 玩家类 -->
        </template>
      </el-table-column>
      <el-table-column label="公司有效投注"
                       align="center"
                       prop="effectiveAmount">
        <template slot-scope="{row}">
            <span>{{row.effectiveAmount | currency}}</span>
          <!-- <span v-if="row.betWays==0"> {{row.effectiveAmount | currency}}</span> <!--平台类-->
           <!-- <span v-else> {{row.playerAmount | currency}}</span> <!--玩家类-->
        </template>
      </el-table-column>
      <el-table-column label="注单号"
                       align="center"
                       width="110px">
        <template slot-scope="{row}">
          {{row.orderId}}
        </template>
      </el-table-column>
      <el-table-column label="所属代理"
                       align="center">
        <template slot-scope="{row}">
          {{row.parentName}}
        </template>
      </el-table-column>
      <el-table-column label="活动流水"
                       align="center"
                       prop="validAmount">
        <template slot-scope="{row}">
          {{row.validAmount | currency}}
        </template>
      </el-table-column>
      <el-table-column label="备注"
                       align="center">
        <template slot-scope="{row}">
          {{row.validRemark}}
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination background
                     @size-change="gridSizeChange"
                     @current-change="gridCurrentChange"
                     :current-page="filters.page"
                     :page-sizes="gridPageSize"
                     :page-size="filters.size"
                     :layout="gridLayout"
                     :total="tableData.total">
      </el-pagination>
    </div>
    <game-dialog v-if="dialogName === 'game-dialog'"
                 v-model="dialogVisible"
                 :row-data="dialogProps"
                 @submit="submitFinished" />
  </div>
</template>

<script>
import {
  form, grid, dialog, pickerOption,
} from '@/build';

import CONST from './CONST';
import {
  gameStatisticListApi as listApi, exportGameManagerDetail,
} from '@/services/api/game';
import GameDialog from './gameDialog';
import { formatChessBetDetail } from './chessBetDetailConfig';

export default {
  name: 'game-detail',
  mixins: [form, grid, dialog, pickerOption],
  components: {
    GameDialog,
  },

  data() {
    const form = this.$route.query;
    const time = form.time ? [moment(form.time[0]).format('YYYY-MM-DD HH:mm:ss'), moment(form.time[1]).format('YYYY-MM-DD HH:mm:ss')] : [moment().format('YYYY-MM-DD 00:00:00'), moment().format('YYYY-MM-DD 23:59:59')];
    return {
      CONST,
      localSummariesText: '当前页汇总 / 所有页汇总',
      dialogName: '',
      lotteryArray: [consts.LB_TICKET, consts.WIN_WIN_LOTTERY, consts.FIVE_GM_LOTTERY],
      form: {
        orderTime: [time[0], time[1]],
        payoutTime: [],
        createTime: [],
        timestamp: [],
        isFake: 0,
      },
      filters: {
        startTime: time[0],
        endTime: time[1],
        payoutStartTime: undefined,
        payoutEndTime: undefined,
        createStartTime: undefined,
        createEndTime: undefined,
        timestampStartTime: undefined,
        timestampEndTime: undefined,
        minAmount: undefined,
        maxAmount: undefined,
        minProfit: undefined,
        maxProfit: undefined,
        gamePlatformId: [1001, 1004, 1003, 7002, 4003, 2001, 10006, 11006, 2003, 13001, 17003, 23004, 18005],
        // channelId: [],
        username: undefined,
        proxy: undefined,
        orderId: undefined,
        merOrderId: undefined,
        status: _.map(consts.NOTE_STATUS, item => item.value),
        page: 1,
        size: 20,
        isFake: 0,
        agGameId: undefined,
        merUsername: '',
      },
      tableData: {
        list: [],
        sum: {
          win: 0,
          prize: 0,
          amount: 0,
          validAmount: 0,
          effectAmount: 0,
        },
        total: 0,
      },
      // statistic: [
      //   {
      //     index: 10,
      //     prop: 'amount',
      //     format: value => <div> {_.currency(value)} / {_.currency(this.tableData.sum.amount)}</div>,
      //   },
      //   {
      //     index: 11,
      //     prop: 'prize',
      //     format: value => <div> {_.currency(value)} / {_.currency(this.tableData.sum.prize)}</div>,
      //   },
      //   {
      //     index: 13,
      //     prop: 'totalWin',
      //     format: value => <div> {_.currency(value)} / {_.currency(this.tableData.sum.win)}</div>,
      //   },
      //   {
      //     index: 14,
      //     prop: 'effectiveAmount',
      //     format: value => <div> {_.currency(value)} / {_.currency(this.tableData.sum.effectAmount)}</div>,
      //   },
      //   {
      //     index: 17,
      //     prop: 'validAmount',
      //     format: value => <div> {_.currency(value)} / {_.currency(this.tableData.sum.validAmount)}</div>,
      //   },
      // ],
      agSubGame: [
        {
          title: '全部',
          value: undefined,
        },
        {
          title: 'XIN',
          value: 301,
        },
        {
          title: 'AG',
          value: 201,
        },
        {
          title: 'YOPALY',
          value: 401,
        },
      ],
      subGameFlag: true,
    };
  },

  methods: {
    resetFilter() {
      this.resetForm('refForm');
      this.submitFilterForm(this.filters);
    },
    transferChannelId() {

    },
    formatBetDetails(betInfo) {
      let { betDetails } = betInfo;
      if (betInfo.game == 3) {
        // 体育投注详情
        let detail = '';
        let { bets } = betInfo;
        if (typeof bets === 'string' && bets != '') {
          bets = JSON.parse(bets);
        }
        _.each(bets, (item) => {
          detail += `联赛：${item.event.tag}双方：${item.event.name}${CONST.sportSelectionNameMap(item.selection)} - ${CONST.sportPeriodNameMap(item.period)} - ${CONST.sportBetTypeMap(item.betType)}，`;
        });
        betDetails = `${detail}等${bets.length}项，共计${_.currency(betInfo.amount)}元`;
      }
      // else if (betInfo.game == 10) {
      //   // 棋牌投注详情
      //   let betInfoBetDeatils = betInfo.betDetails;
      //   if (typeof betInfoBetDeatils === 'string' && betInfoBetDeatils != '') {
      //     betInfoBetDeatils = JSON.parse(betInfoBetDeatils);
      //   }
      //   betDetails = formatChessBetDetail(betInfo.gameName, betInfoBetDeatils);
      // }
      return betDetails;
    },
    checkShowDetail(row) {
      if ([consts.PLATFORM_JOY_POKER, consts.PLATFORM_GM_POKER].includes(row.gamePlatformId)) {
        return '';
      }
      return row.betDetails;
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];

      columns.forEach((column, index) => {
        const values = data.map((item) => {
          if (index === 11 && item.betWays === 1) {
            return Number(item.playerPrize);
          }
          return Number(item[column.property]);
        });
        if (index === 0) {
          sums[index] = '当前页汇总 / 所有页汇总';
          return;
        } if ([10, 11, 13, 14, 17].indexOf(index) !== -1 && !values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            }
            return prev;
          }, 0);
          let totalData = '';
          switch (index) {
            case 10:
              totalData = _.currency(this.tableData.sum.amount);
              break;
            case 11:
              totalData = _.currency(this.tableData.sum.prize);
              break;
            case 13:
              totalData = _.currency(this.tableData.sum.win);
              break;
            case 14:
              totalData = _.currency(this.tableData.sum.effectAmount);
              break;
            case 17:
              totalData = _.currency(this.tableData.sum.validAmount);
              break;
          }
          sums[index] = `${_.currency(sums[index])}/${totalData}`;
        } else {
          sums[index] = '';
        }
      });

      return sums;
    },
  },

  mounted() {
    const { gamePlatformId } = this.$route.query;
    if (gamePlatformId !== undefined && Number(gamePlatformId) !== 8000) {
      this.filters.gamePlatformId = [gamePlatformId];
    }
    this.bindGet(listApi, 'tableData', {
      action: 'getGrid',
      sendingData: 'form',
      beforeSend: (data) => {
        let {
          orderTime, payoutTime, createTime, timestamp,
        } = data;
        if (!orderTime || orderTime.length !== 2) {
          orderTime = [undefined, undefined];
        }
        if (!payoutTime || payoutTime.length !== 2) {
          payoutTime = [undefined, undefined];
        }
        if (!createTime || createTime.length !== 2) {
          createTime = [undefined, undefined];
        }
        if (!timestamp || timestamp.length !== 2) {
          timestamp = [undefined, undefined];
        }
        return {
          ...this.filters,
          startTime: orderTime[0],
          endTime: orderTime[1],
          payoutStartTime: payoutTime[0],
          payoutEndTime: payoutTime[1],
          createStartTime: createTime[0],
          createEndTime: createTime[1],
          timestampStartTime: timestamp[0],
          timestampEndTime: timestamp[1],
          gamePlatformId: this.filters.gamePlatformId.join(','),
          status: this.filters.status.join(','),
          // gameId: this.filters.gameId.join(','),
          // channelId: this.filters.gameId.length > 0 ? this.channelIdFormat(this.filters.gameId) : '',
        };
      },
      format: (data) => {
        const tableList = _.map(data.list, (item) => {
          item.betDetails = this.formatBetDetails(item);
          if (item.game == 10 && item.game == 11) {
            item.gameResult = item.win > 0 ? '输' : (item.win == 0 ? '和' : '赢');
          }
          return item;
        });
        data.list = tableList;
        return data;
      },
    });
    this.doGet({ action: 'getGrid' });
    this.bindGet(exportGameManagerDetail, '', {
      action: 'getExportExcel',
      sendingData: 'form',
      beforeSend: (data) => {
        let {
          orderTime, payoutTime, createTime, timestamp,
        } = data;
        if (!orderTime || orderTime.length !== 2) {
          orderTime = [undefined, undefined];
        }
        if (!payoutTime || payoutTime.length !== 2) {
          payoutTime = [undefined, undefined];
        }
        if (!createTime || createTime.length !== 2) {
          createTime = [undefined, undefined];
        }
        if (!timestamp || timestamp.length !== 2) {
          timestamp = [undefined, undefined];
        }
        return {
          ...this.filters,
          startTime: orderTime[0],
          endTime: orderTime[1],
          payoutStartTime: payoutTime[0],
          payoutEndTime: payoutTime[1],
          createStartTime: createTime[0],
          createEndTime: createTime[1],
          timestampStartTime: timestamp[0],
          timestampEndTime: timestamp[1],
          gamePlatformId: this.filters.gamePlatformId.join(','),
          status: this.filters.status.join(','),
          // gameId: this.filters.gameId.join(','),
          // channelId: this.filters.gameId.length > 0 ? this.channelIdFormat(this.filters.gameId) : '',
        };
      },
      callback:([result,data])=>{
        if(!result){
          this.$message({
            type: 'error',
            message: data.message,
          })
        }else{
          this.$message({
            type: 'warning',
            message: '正在导出，请稍后下载',
          })
        }
      }
    });
  },
  watch: {
    'filters.gamePlatformId': function (val) {
      if (val.length === 1 && val.includes(1003)) {
        this.subGameFlag = false;
      } else {
        this.subGameFlag = true;
        this.filters.agGameId = undefined;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.form-center-tip {
  line-height: 36px;
  padding-right: 10px;
}
</style>
